
package com.zy.Conterller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
@Slf4j
public class LoginCount {
    @GetMapping("login")
    public String login() {

        return "login";
    }

    @PostMapping("login")
    public String login(String userCode, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userCode, password);
        subject.login(token);
        log.info("用户登陆成功" + subject.isAuthenticated());
        return "redirect:/index";
    }

    @ExceptionHandler({RuntimeException.class})
    //局部异常
    public void handlerEx(RuntimeException e, Model model){
        String msg ="";
        if(e instanceof UnknownAccountException){
            msg="用户名密码错误";

        }else if(e instanceof IncorrectCredentialsException){
            msg="用户名或者密码错误";
        }else{
            msg="其他错误";
        }
        model.addAttribute("loginErr",msg);
    }
}